#ifndef _LOG_MANAGER_H
#define _LOG_MANAGER_H

#include <stdio.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>

#define LOG_ERROR   "[error]"
#define LOG_STAT    "[stat]"
#define LOG_WARING  "[waring]"
#define LOG_FAILED  "[filed]"
#define LOG_EXIT    "[exit]"
#define LOG_EVENT   "[event]"

FILE *log_fp;
char time_str[20] = {0}, time_file[20] = {0}; 
char fileName[256] = {0};
int init = 0;

#ifndef LOGFILE
#define LOGFILE "/home/wyf/.log/"
#endif

#define LOG_MANAGE(level, frm, ...) { \
    /*printf("%s\n", LOGFILE);*/ \
    if (init == 0) { char initPath[1024] = {0}; sprintf(initPath, "mkdir -p %s", LOGFILE); system(initPath); init = 1;} \
    getInfo(); \
    if (log_fp == NULL) { \
        /*printf("opening file\n");*/ \
        log_fp = fopen(fileName, "a+"); \
    } \
    /*printf("after open file\n");*/ \
    /*printf("after get time_str\n");*/ \
    /*if (!log_fp) printf("log_fp is null\n");*/ \
    fprintf(log_fp, "%s %s "frm, time_str, level, ##__VA_ARGS__); \
}

static void getInfo() {
    time_t now = time(NULL); 
    // if (time_str[0] == '\0' || time_file[0] == '\0') {
    if (fileName[0] == '\0') {
        strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", localtime(&now)); 
        strftime(time_file, sizeof(time_file), "%Y%m%d", localtime(&now)); 
    } else {
        char tmp[20] = {0};
        strftime(tmp, sizeof(tmp), "%Y%m%d", localtime(&now)); 
        if (tmp[strlen(tmp) - 2] == '0' && tmp[strlen(tmp) - 1] == '1') {
            // printf("get time\n");
            strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", localtime(&now)); 
            strftime(time_file, sizeof(time_file), "%Y%m%d", localtime(&now)); 
            char tarStr[1024] = {0};
            sprintf(tarStr, "tar -czf %s.tar.gz %s 2>/dev/null", fileName, fileName);
            // printf("%s\n", tarStr);
            system(tarStr);
            if (log_fp != NULL) {
                fclose(log_fp);
            }
        }
    }
    sprintf(fileName, "%s/slaveInfo-%s.log", LOGFILE, time_file); 
}

#endif
